<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use DB;
use EasyWeChat;

class CheckSellOrders extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'book-shop:checkSellOrders';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '检测卖书订单';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $this->info("开始获取...");

        $now_time = time();
        $officialAccount = EasyWeChat::officialAccount(); // 公众号
        $orders = DB::table('sell_orders')->where('express_ready_get_push',0)->where('state',2)->get();
        if(!empty($orders))
        {
            foreach ($orders as $v)
            {
                //在用户预约上门时间的前90分钟，对没有取消的该状态下的卖书订单，进行该条消息的推送
                if(($v->express_time - $now_time) <= 5400)
                {
                    $user = DB::table('users')->where('id',$v->user_id)->first();
                    $wechat_user = DB::table('wechat_users')->where('unionid',$user->unionid)->first();
                    if(!empty($wechat_user))
                    {
                        $openid = $wechat_user->openid;

                        $first = "我们为您安排的顺丰快递预计在1小时内联系您免费上门取书，请保持手机畅通。\r";
                        $officialAccount->template_message->send([
                            'touser'        => $openid,
                            'template_id'   => 'fDri6AUO73KHgibmDn8v8vm1esCaNMCML_eesYlb6Ns',
                            'url'  => '',
                            'miniprogram' => [
                                'appid'     => config('wechat.mini_program.default.app_id'),
                                'path'  => '/pages/sale/order/order-detail/order-detail?id='.$v->id
                            ],
                            'data' => [
                                'first'         => $first,
                                'OrderSn'       => $v->no,
                                'OrderStatus'   => '待快递上门取书'."\r\n",
                                'remark'        => '如需打包箱等物料，可在快递员联系你时和他说明，所有费用均为到付。'
                            ],
                        ]);
                    }

                    DB::table('sell_orders')->where('id',$v->id)->update(['express_ready_get_push' => 1]);
                }
            }
        }

        $this->info("获取成功...");
    }
}
